# encoding=utf-8
import csv
import json
import os
import sys
import threading
import time

import requests

abs_path = os.path.split(sys.argv[0])[0]


# 将请求的数据, 转换成json数据
def get_true_json(conn, key=False):
    index = conn.find('(') + 1
    conn = conn[index:-2]
    if not key:
        return conn
    else:
        return json.loads(conn, encoding='utf-8')


# 获取音乐数据
def get_data_json():
    data_url = 'https://songsearch.kugou.com/song_search_v2?callback=jQuery112402604825070239274_1559924368720&keyword=qq%E9%A3%9E%E8%BD%A6&page=1&pagesize=100&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1559924368726'

    conn = requests.get(url=data_url)
    conn.encoding = 'utf-8'

    conn = get_true_json(conn.text)
    with open('data.json', 'w', encoding='utf-8') as f:
        f.write(conn)
    print(conn)


# 打印json数据
def data_print_to_save_csv():
    file_path = abs_path + '/' + 'data.json'
    with open(file_path, 'r', encoding='utf-8') as f:
        jsonStr = json.load(f)
        try:
            music_lists = jsonStr[0]['data']['song']
        except Exception as e:
            music_lists = jsonStr['data']['lists']

        for i in music_lists:
            if i.get('hash'):
                print('hash : ', i.get('hash'), 'albumID : ', i.get('AlbumID'))
                print(i.get('songname'), '--', i.get('singername'))
                hash = i.get('hash')
                AlbumID = str(i.get('AlbumID'))
            else:
                hash = i.get('FileHash')
                AlbumID = i.get('AlbumID')
                print('FileHash : ', hash, 'albumID : ', AlbumID)
                print(i.get('FileName'))
            # url需要 hash 和音乐 albumid
            url = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19108399584051974596_1559657369367&hash=%s&' \
                  'album_id=%s&' \
                  'dfid=3v4sCD1xdbzr0AaEpN1hUKUI&mid=08f708b454f6ffe7fc8e7d6a2580580d&platid=4&_=1559657369813' % (
                      hash, AlbumID)
            conn = requests.get(url=url)
            conn.encoding = 'utf-8'
            conn = get_true_json(conn.text, True)
            data = conn['data']
            audio_name = data.get('audio_name')
            author_name = data.get('author_name')
            song_name = data.get('song_name')
            play_url = data.get('play_url')
            lyrics = data.get('lyrics')

            print([audio_name, author_name, song_name, play_url, lyrics])
            save_csv([audio_name, author_name, song_name, play_url])
            save_lyric(audio_name, lyrics)
            time.sleep(5)


# 保存 list 为csv文件
def save_csv(list_li):
    thLock = threading.Lock()
    thLock.acquire()
    file_path = abs_path + '/' + 'music_url.csv'
    f = open(file_path, 'a+', encoding='utf-8', newline='')
    writer = csv.writer(f)
    writer.writerow(list_li)
    f.close()
    thLock.release()


# 下载歌曲, 需要创建 music文件夹
def download_music():
    folder_path = abs_path + '/' + 'music/'
    if not os.path.isdir(folder_path):
        os.mkdir(folder_path)

    read_file_path = abs_path + '/' + 'music_url.csv'
    with open(read_file_path, 'r', encoding='utf-8') as f:
        music_li = csv.reader(f)
        for i in music_li:
            audio_name = i[0]  # 歌手 - 歌曲名
            author_name = i[1]  # 歌手
            song_name = i[2]  # 歌名
            play_url = i[3]  # 歌曲url
            music_type = play_url.split('.')[-1]

            print(audio_name, play_url, music_type)

            if '' == play_url:
                continue
            try:
                conn = requests.get(play_url)
                with open(folder_path + audio_name + '.' + music_type, 'wb') as f:
                    f.write(conn.content)
                time.sleep(5)
            except Exception as e:
                with open(abs_path + '/' + 'error.txt', 'a+') as f:
                    f.write(audio_name + '\n')
                    f.write(play_url + '\n')
                    f.write('--------------------------' + '\n')


# 保存歌词文件
def save_lyric(name, words):
    thLock = threading.Lock()
    file_type = '.lrc'
    folder_path = abs_path + '/' + 'lyric/'
    if not os.path.isdir(folder_path):
        os.mkdir(folder_path)

    thLock.acquire()
    if words == '':  # 歌词为空返回
        return
    if '' == name:  # 文件名称为空,获取时间帧为文件名
        name = str(time.time_ns())
    file_path = folder_path + name + file_type

    f = open(file_path, 'w', encoding='utf-8')
    f.write(words)
    f.close()
    thLock.release()


# 记录 data.json 数据
def count_data_json():
    with open('data.json', 'r', encoding='utf-8') as f:
        jsonStr = json.load(f)
        json_li = jsonStr['data']['lists']
        for i in json_li:
            print(i)

        print('json list count : ', len(json_li))


if __name__ == '__main__':
    get_data_json()
    data_print_to_save_csv()
    download_music()

    # count_data_json()

    # save_lyric('hehehe', 'fjdsaoejfaslkjfioeajfdklsjafioejfals')
